<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/17
 * Time: 15:40
 */

//定义mysql操作类
namespace Shop;

if(!defined("SHOP")){
    header("Location:../index.php");
}

class Model{
    //属性
    private $host; //地址
    private $port; //端口
    private $user; //用户
    private $pass; //密码
    private $dbname; //库名
    private $charset; //字符集

    private $obj; //pdo对象

    //初始化属性
    //$info 初始化的数据
    function __construct()
    {
        //读取配置文件里面的配置
        $this->host=$GLOBALS['Config']['db_host'];
        $this->port=$GLOBALS['Config']['db_port'];
        $this->user=$GLOBALS['Config']['db_user'];
        $this->pass=$GLOBALS['Config']['db_pass'];
        $this->dbname=$GLOBALS['Config']['db_name'];
        $this->charset=$GLOBALS['Config']['db_charset'];

        //初始化
        $this->pdo_connect();

    }

    //连接认证
    private function pdo_connect(){
        try {
            //再有命名空间的类里面实例化系统类必须用访问全局的方式 \
            $this->obj = new \PDO("mysql:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}", "{$this->user}", "{$this->pass}");
            //设置错误为异常
            $this->obj->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION);
        }catch(\PDOException $e){
            echo "连接错误！<br/>";
            echo "错误信息：".$e->getMessage();
            exit;
        }
    }

   //定义修改方法--给定义的模型使用
    public function pdo_exec($sql){
        try{
            return $this->obj->exec($sql);
        }catch(\PDOException $e){
            echo "sql错误！<br/>";
            echo "错误信息：".$e->getMessage();
            exit;
        }
    }

    //定义高级插入方法
//    $table  数据表
//   $arr      数据
    public function pdo_insert($table,$arr){
        $sql="insert into $table set ";
        foreach($arr as $k=>$v){
            //$k 字段名 $v 值
            $sql.=" `$k` = '$v',";
        }
        $sql=trim($sql,',');
        $this->pdo_exec($sql);
        //返回 自增长的id
        return $this->obj->lastInsertId();
    }

    //高级修改
    public function pdo_upd($table,$arr,$where){
        $sql="update $table set ";
        foreach($arr as $k=>$v){
            //$k 字段名 $v 值
            $sql.=" `$k` = '$v',";
        }
        $sql=trim($sql,',');
        $sql.=$where;
       return $this->pdo_exec($sql);
    }

    //查询方法
//    $type =1 查询单条 ，2查询多条
    public function pdo_sel($sql,$type=1){
        try{
            $res=$this->obj->query($sql);
            if($type == 1){
                //单条
                return $res->fetch(\PDO::FETCH_ASSOC);
            }else{
                //多条
                return $res->fetchAll(\PDO::FETCH_ASSOC);
            }
        }catch(\PDOException $e){

        }
    }
}